//
//  LoadData.m
//  食为天
//
//  Created by lanou3g on 14-8-17.
//  Copyright (c) 2014年 三个屌丝. All rights reserved.
//

#import "LoadData.h"
#import "JTCSM.h"
@implementation LoadData

+ (instancetype)object{
   static LoadData *load;
    if (load == nil) {
        load = [[LoadData alloc]init];
    }
    
    return load;
}


//GET异步请求
 - (void)loadDataAsynchronousWithURL:(NSString *)url Block:(LoadDataBlock) block
{
         self.loadData = block;
         
         NSURL *URL=[NSURL URLWithString:url];
        
         NSURLRequest *request=[[NSURLRequest alloc] initWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
         [NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)loadDataAsynchronousWithURL:(NSString *)url withDic:(NSDictionary *)dict superView:(UIView *)fahter Block:(LoadDataBlock) block{
    
    if (fahter != nil) {
        [df showWaiting:fahter];
        self.vi = fahter;
    }
    
    self.loadData = block;
    for (int i = 0; i < [dict allKeys].count; i++) {
        if (i == 0) {
            NSString *str = [NSString stringWithFormat:@"%@=%@",[dict allKeys][i],[dict allValues][i]];
            url = [url stringByAppendingString:str];
        }else{
            NSString *str = [NSString stringWithFormat:@"&%@=%@",[dict allKeys][i],[dict allValues][i]];
            url = [url stringByAppendingString:str];
        }
    }
    NSURL *URL=[NSURL URLWithString:url];
    
    NSURLRequest *request=[[NSURLRequest alloc] initWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [NSURLConnection connectionWithRequest:request delegate:self];

}
- (NSString *)HTTPBodyWithParameters:(NSDictionary *)parameters
{
    NSMutableArray *parametersArray = [[NSMutableArray alloc]init];
    
    for (NSString *key in [parameters allKeys]) {
        id value = [parameters objectForKey:key];
        NSString *valueStr = [NSString stringWithFormat:@"%@",value];
        if ([valueStr isKindOfClass:[NSString class]]) {
          NSString *str = [valueStr stringByReplacingOccurrencesOfString:@"\"" withString:@""];
            [parametersArray addObject:[NSString stringWithFormat:@"%@:%@",key,str]];
        }
        
    }
    
    return [parametersArray componentsJoinedByString:@"&"];
}
//Post异步请求
- (void)loadDataPostAsynchronousWithURL:(NSString *)url withDict:(NSDictionary *)dict Block:(LoadDataBlock) block{
    self.loadData = block;
    
    json =  [self HTTPBodyWithParameters:dict];
    //拼接请求参数
    //对字符串进行编码后转成NSData对象
    NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
    //创建url
    //请求地址
    
    NSString *urlString = url;
    
    //初始化一个NSURL对象
    
    NSURL *urlStr = [NSURL URLWithString:urlString];
    
    //初始化一个请求
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlStr];
    
    //        request.allHTTPHeaderFields = dict;
    //设置请求方法，可以省略，缺省GET请求
    
    request.HTTPMethod = @"POST";
    
    //如果60秒过后服务器还没有响应，就算请求超时
    
    request.timeoutInterval = 30;
    
    //设置请求体
    request.HTTPBody = data;
    
    /*
     
     //设置请求头信息-请求体长度
     
     NSString *contentLength = [NSString stringWithFormat:@"%i",data.length];
     
     [request setValue:contentLength forHTTPHeaderField:@"Content-Length"];
     
     //设置请求头信息-请求数据类型
     
     [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
     
     可以省略部分，只要设置请求体，系统在发送的时候会在根据请求体自动加上相应的请求头信息的。
     
     */
    
    //初始化一个连接
    
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    
    //开始一个异步请求,缺省异步请求
    
    [conn start];
    
    
}
- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

//Post异步请求
- (void)loadDataPostAsynchronousWithURL:(NSString *)url withDict:(NSDictionary *)dict superView:(UIView *)fahter isAddtag:(BOOL)isaddtag Block:(LoadDataBlock) block{
    
    if (fahter != nil) {
        [df showWaiting:fahter];
        self.vi = fahter;
    }
        self.loadData = block;
    isaddTishi = isaddtag;
    NSData *data = [NSData data];
    if (dict != nil) {
        json = [NSString stringWithFormat:@"p=%@",[self dictionaryToJson:dict]];
        //拼接请求参数
        //对字符串进行编码后转成NSData对象
        data = [json dataUsingEncoding:NSUTF8StringEncoding];
    }
    
    
    
        //创建url
        //请求地址
        
        NSString *urlString = url;
        //初始化一个NSURL对象
        
        NSURL *urlStr = [NSURL URLWithString:urlString];
        
        //初始化一个请求
    
    
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlStr];
    
//        request.allHTTPHeaderFields = dict;
        //设置请求方法，可以省略，缺省GET请求
        
        request.HTTPMethod = @"POST";
        
        //如果60秒过后服务器还没有响应，就算请求超时
        
        request.timeoutInterval = 30;
    
           //设置请求体
        request.HTTPBody = data;
    
        /*
        
         //设置请求头信息-请求体长度
        
         NSString *contentLength = [NSString stringWithFormat:@"%i",data.length];
        
         [request setValue:contentLength forHTTPHeaderField:@"Content-Length"];
        
         //设置请求头信息-请求数据类型
         
         [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
         
         可以省略部分，只要设置请求体，系统在发送的时候会在根据请求体自动加上相应的请求头信息的。
         
         */
        
        //初始化一个连接

        NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
        
        //开始一个异步请求,缺省异步请求
        
        [conn start];
    

}

//接收到服务器回应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //接受到会用的时候,创建一个可变的data 用于存储服务器传送过来的数据
    self.receiveData=[NSMutableData data];
    
}
//接到服务器  传送过来的数据  这个方法可能会执行多次(服务器发得数据比较大得时候  会分多次发送  我们会接受多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //拼接服务器发送过来的数据
    [self.receiveData appendData:data];
}

//数据接受完毕  或者 数据上传完毕
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [df hideWaiting:self.vi];
    
   // NSLog(@"%@",self.receiveData);
    id result = [NSJSONSerialization JSONObjectWithData:self.receiveData options:NSJSONReadingMutableLeaves error:nil];
    NSString *ireturn = [NSString stringWithFormat:@"%@",KResultOfKey(@"status")];
    if ([ireturn isEqualToString:@"-2"] || [ireturn isEqualToString:@"-1"]|| [ireturn isEqualToString:@"-3"]) {
        [df showAlertWithTitle:[result objectForKey:@"msg"] message:nil btn1:@"知道了" btn2:nil btn3:nil delegate:self tag:121];
        KUSERDEFAULTRemoveAll(KInfoKey);
        [df gotoLoginVC:[JTCSMSingle shareSingle].navigationC];

        return;
    }
    
    if (isaddTishi) {
        
        alertLabel = [UILabel initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width-100)/2, [UIScreen mainScreen].bounds.size.height-100, 100, 30) text:[result objectForKey:@"msg"] font:16 textAlignment:NSTextAlignmentCenter texcolor:[UIColor whiteColor] backgroundColor:[UIColor blackColor]];
        [df layerWithView:alertLabel radius:4 width:0 color:nil];
        [[JTCSMSingle shareSingle].theWindow addSubview:alertLabel];
        
      CGRect rect = [df labelHeightWithContent:alertLabel.text height:30 label:alertLabel];
        
        alertLabel.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width-rect.size.width-20)/2, [UIScreen mainScreen].bounds.size.height-100, rect.size.width+20, 30);
        
        timer= [NSTimer scheduledTimerWithTimeInterval:3 target:self
                                              selector:@selector(showRepeatButton)
                                              userInfo:nil
                                               repeats:YES];
        
    }
    if (result == nil) {
//        return ;
        _loadData([[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding]);
    }else{
        _loadData(result);
    }

    //NSLog(@"    %@",result);

}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [df hideWaiting:self.vi];
}
#pragma UIalertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag == KAlertVTag +121) {
        KUSERDEFAULTRemoveAll(KInfoKey);
        [df gotoLoginVC:[JTCSMSingle shareSingle].navigationC];


    }
}


//GET同步GET请求
- (void)loadDataSynchronousWithURL:(NSString *)url Block:(LoadDataBlock)block
{
    
        self.loadData=block;
        
        NSURL *URL=[[NSURL alloc] initWithString:url];
   // NSLog(@"%@",URL);
        NSURLRequest *request=[[NSURLRequest alloc] initWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
        
        NSURLResponse *response=nil;
        NSError *error=nil;
        
        
        NSData *data =  [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        _loadData(result);

    
    
}
- (void)loadDataSynchronousWithURL:(NSString *)url dict:(NSDictionary *)dict  Block:(LoadDataBlock)block{
    for (int i = 0; i < [dict allKeys].count; i++) {
        if (i == 0) {
            NSString *str = [NSString stringWithFormat:@"%@=%@",[dict allKeys][i],[dict allValues][i]];
            url = [url stringByAppendingString:str];
        }else{
            NSString *str = [NSString stringWithFormat:@"&%@=%@",[dict allKeys][i],[dict allValues][i]];
            url = [url stringByAppendingString:str];
        }
    }
    self.loadData=block;
    
    NSURL *URL=[[NSURL alloc] initWithString:url];
    
    NSURLRequest *request=[[NSURLRequest alloc] initWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    
    NSURLResponse *response=nil;
    NSError *error=nil;
    
    
    NSData *data =  [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (data == nil) {
        _loadData(nil);
        
    }else{
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        _loadData(result);
    }
    


}

- (void)showRepeatButton{
    [timer invalidate];
    [alertLabel removeFromSuperview];
    alertLabel = nil;
}


@end
